package com.zzptc.lxy.mybook;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.zzptc.lxy.mybook.Utils.ProcessText;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

public class ReadActivity extends AppCompatActivity {
    ListView bookpagelv;
    EditText pageedit;
    Button getPre,getNext,getAppoint;
    ImageView bimg;
    ScrollView scroll;
    TextView readtxt,pagetxt,bname,aname;
    String content;
    String filepath="/sdcard/Download/";
    ProcessText processText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_read);
        initView();
        setListener();

        
    }
//    获取页码
    private void getPage(){
        pagetxt.setText("第"+processText.currentpage+"页"+"/共"+processText.pages+"页");
    }
    private void setListener() {
        View.OnClickListener listener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()){
                    case R.id.getPre:
                        content=processText.getPre();
                        readtxt.setText(content);
                        getPage();
                        scroll.scrollTo(0,0);
                        break;
                    case R.id.getNext:
                        content=processText.getNext();
                        readtxt.setText(content);
                        getPage();
                        scroll.scrollTo(0,0);
                        break;
                    case R.id.getAppoint:
                        long appointpage= Long.parseLong(pageedit.getText().toString());
                        content=processText.getAppoint(appointpage);
                        readtxt.setText(content);
                        getPage();
                        scroll.scrollTo(0,0);
                        break;
                }
            }
        };
        getAppoint.setOnClickListener(listener);
        getPre.setOnClickListener(listener);
        getNext.setOnClickListener(listener);
        pageedit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!s.toString().equals("")){
                    long page= Long.parseLong(s.toString());
                    Log.e("after",page+"");
                    if (page>processText.pages){
                        pageedit.setText(processText.pages+"");
                    } else if (page<1){
                        pageedit.setText(1+"");
                    }
                }
            }
        });

        bookpagelv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Log.e("page",id+"");
                content=processText.getAppoint(id+1);
                readtxt.setText(content);
                getPage();
                scroll.scrollTo(0,0);
            }
        });
    }

    private void initView() {
        readtxt=findViewById(R.id.readtxt);
        pagetxt=findViewById(R.id.pagetxt);
        bimg=findViewById(R.id.bookimg);
        bname=findViewById(R.id.bookname);
        aname=findViewById(R.id.authorname);
        bookpagelv=findViewById(R.id.bookpagelv);
        pageedit=findViewById(R.id.pageedit);
        getPre=findViewById(R.id.getPre);
        getNext=findViewById(R.id.getNext);
        getAppoint=findViewById(R.id.getAppoint);
        scroll=findViewById(R.id.scroll);

        Intent it=getIntent();
        int bookimg=it.getIntExtra("bookimg",-1);
        String bookname=it.getStringExtra("bookname");
        String authorname=it.getStringExtra("authorname");
        bimg.setImageResource(bookimg);
        bname.setText(bookname);
        aname.setText("作者："+authorname);
        String str=readAssetsTxt(bookname);
        File file=new File(filepath+bookname);
        if (!file.exists()){
            file=writeTxtToFile(str,filepath,bookname);
        }
        processText=new ProcessText(file,0);
        content=processText.getNext();
        readtxt.setText(content);
        getPage();
        setMenulv();
    }

    private void setMenulv() {
        long pages=processText.pages;
        List<String> pagestr=new ArrayList<>();
        for (long i=1;i<=pages;i++){
            pagestr.add("第"+i+"页");
        }
        ArrayAdapter<String> adapter=new ArrayAdapter<>(ReadActivity.this,android.R.layout.simple_list_item_1,pagestr);
        bookpagelv.setAdapter(adapter);
    }


    public String readAssetsTxt(String fileName){
        try {
            InputStream is = getAssets().open(fileName+".txt");
            int size=is.available();
            byte[] buffer=new byte[size];
            is.read(buffer);
            is.close();
            String text=new String(buffer,"utf-8");
            return text;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "读取错误，请检查文件名";
    }


    public File writeTxtToFile(String strcontent, String filePath, String fileName) {
        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            FileOutputStream fos=new FileOutputStream(file,false);
            fos.write(strContent.getBytes());
            fos.close();
//            if (!file.exists()) {
//                Log.d("TestFile", "Create the file:" + strFilePath);
//                file.createNewFile();
//            }
//            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
//            raf.seek(0);
//            raf.write(strContent.getBytes());
//            raf.close();
            return file;
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
        return null;
    }
//    public File makeFilePath(String filePath, String fileName) {
//        File file = null;
//        makeDirectory(filePath);
//        try {
//            file = new File(filePath + fileName);
//            if (!file.exists()) {
//                file.createNewFile();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return file;
//    }
//
//    // 生成文件夹
//    public static void makeDirectory(String filePath) {
//        File file = null;
//        try {
//            file = new File(filePath);
//            if (!file.exists()) {
//                file.mkdir();
//            }
//        } catch (Exception e) {
//            Log.i("error:", e+"");
//        }
//    }
}
